<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词挑战</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="grade-3.js"></script>
</head>
<body>
<div id="app" class="container">
    <div class="main-content">
        <!-- 挑战区域 -->
        <div class="challenge-section">
            <div class="word-display" v-if="isStarted && !isFinished">
                <span class="grade-badge">{{currentWord.group}}</span>
                <span v-if="currentWord.wrong_weight>0" class="weight-badge">易错</span>
                <div class="word-text">{{ currentWord.chinese }}</div>
            </div>
            <input class="answer" v-model="userAnswer" v-if="isStarted && !isFinished" v-focus :disabled="isAnswered"
                   @keyup.enter="checkAnswer" :placeholder="waitingForCorrectAnswer ? '请重新输入正确答案' : '请输入英文单词'">
            
            <!-- 答题反馈 -->
            <div class="answer-feedback" v-if="showFeedback" :class="feedbackType">
                <div class="feedback-icon">{{feedbackType === 'correct' ? '✓' : '✗'}}</div>
                <div class="feedback-content">
                    <div class="feedback-message">{{feedbackMessage}}</div>
                    <div class="feedback-details" v-if="feedbackType === 'incorrect'">
                        <span>正确答案: <strong>{{currentWord.english}}</strong></span>
                    </div>
                    <div class="feedback-hint" v-if="!waitingForCorrectAnswer">等待自动进入下一题</div>
                </div>
                <button class="feedback-close" @click="hideFeedback">&times;</button>
            </div>
            
            <!-- 当前挑战记录 -->
            <div class="listen-records" v-if="listenRecords.length > 0">
                <h3>本次挑战进度</h3>
                <div class="progress-bar">
                    <div class="progress-fill" :style="{width: (listenRecords.length / listenCount * 100) + '%'}"></div>
                </div>
                <div class="progress-text">{{listenRecords.length}} / {{listenCount}}</div>
            </div>
            
            <button class="btnStart" @click="startListening" v-if="!isStarted || isFinished">
                {{listenRecords.length > 0 ? '重新' : ''}}开始挑战
            </button>
        </div>

        <!-- 挑战记录区域 -->
        <div class="records-section">
            <h2>挑战记录</h2>
            <div class="challenge-records">
                <div class="challenge-record-item" 
                     v-for="(record, index) in challengeRecords" 
                     :key="index"
                     @click="showRecordDetail(record)"
                     :class="{'success': record.is_success, 'failed': !record.is_success}">
                    <div class="record-content">
                        <span class="record-time">{{record.finish_time}}</span>
                        <span class="record-stats-inline">
                            <span class="stat-item">正确: {{record.correct_count}}</span>
                            <span class="stat-item">错误: {{record.wrong_count}}</span>
                            <span class="stat-item">总计: {{record.words.length}}</span>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 挑战记录详情弹窗 -->
    <div class="modal-overlay" v-if="showDetail" @click="closeDetail">
        <div class="modal-content" @click.stop>
            <div class="modal-header">
                <h4>挑战详情 - {{selectedRecord.finish_time}}</h4>
                <button class="close-btn" @click="closeDetail">&times;</button>
            </div>
            <div class="modal-body">
                <div class="detail-words">
                    <div class="word-detail-grid">
                      <div class="word-column incorrect-column">
                          <h4 class="column-title">✗ 错误题目</h4>
                          <div class="word-list">
                              <div class="word-detail-item incorrect" 
                                  v-for="(record, index) in selectedRecord.records.filter(r => !r.isCorrect)" 
                                  :key="'incorrect-' + index">
                                  <div class="word-detail-content">
                                      <span class="word-number">{{selectedRecord.records.indexOf(record) + 1}}.</span>
                                      <span class="word-chinese">{{record.word.chinese}}</span>
                                      <span class="word-english"><b>({{record.word.english}})</b></span>
                                      <span class="word-separator">|</span>
                                      <span class="user-answer" v-if="record.answer" :class="{'wrong-answer': !record.isCorrect}">
                                        {{record.answer}}
                                      </span>
                                  </div>
                              </div>
                          </div>
                      </div>
                        <div class="word-column correct-column">
                            <h4 class="column-title">✓ 正确题目</h4>
                            <div class="word-list">
                                <div class="word-detail-item correct" 
                                     v-for="(record, index) in selectedRecord.records.filter(r => r.isCorrect)" 
                                     :key="'correct-' + index">
                                    <div class="word-detail-content">
                                        <span class="word-number">{{selectedRecord.records.indexOf(record) + 1}}.</span>
                                        <span class="word-chinese">{{record.word.chinese}}</span>
                                        <span class="word-english">({{record.word.english}})</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
  Vue.directive('focus', {
    inserted: function (el) {
      el.focus();
    }
  });
  new Vue({
    el: '#app',
    data: {
      selectedWords: [],
      listenRecords: [],
      challengeRecords: [],
      currentWordIndex: 0,
      currentWord: null,
      listenCount: 25,// 每次听写的单词数
      userAnswer: '',
      isAnswered: false,
      isStarted: false,
      isFinished: false,
      correctCount: 0,
      showDetail: false,
      selectedRecord: null,
      showFeedback: false,
      feedbackType: null,
      feedbackMessage: '',
      waitingForCorrectAnswer: false,
    },
    mounted() {
      this.challengeRecords = JSON.parse(localStorage.getItem('challenge_records')) || []
      let listening = JSON.parse(localStorage.getItem('listening'))
      if (listening) {
        this.selectedWords = listening.words
        this.currentWordIndex = listening.current + 1
        this.listenRecords = listening.records
        this.isStarted = true
        this.correctCount = listening.correct_count
        this.isFinished = listening.current >= this.listenCount - 1
        this.showCurrentWord()
      }
      
      // 添加键盘事件监听
      document.addEventListener('keydown', this.handleKeydown);
    },
    beforeDestroy() {
      // 移除键盘事件监听
      document.removeEventListener('keydown', this.handleKeydown);
    },
    methods: {
      selectWords() {
        let weightedList = []
          , wrongWeights = this.getWrongWeights()

        let time_weight = 0
        words3_2.forEach(word => {
          let groups = [
            'KB-U1','KB-U2',
            'KB-U3','KB-U4',
            'KB-U5','KB-U6',
            'KB-U7','KB-U8',
            '京版'
          ];
          if (groups.includes(word.group)) {
            time_weight++
            let wrongWeight = wrongWeights[word.english] || 0
            word.wrong_weight = wrongWeight
            word.weight = 30 + time_weight * wrongWeight
            weightedList[word.english] = word
          }
        })

        weightedList = Object.values(weightedList)
        // 计算权重总和
        const totalWeight = weightedList.reduce((sum, word) => sum + word.weight, 0);

        // 构建轮盘
        let roulette = [];
        let currentWeight = 0;
        for (let word of weightedList) {
          currentWeight += word.weight;
          word.upperBound = currentWeight;
          roulette.push(word);
        }

        // 随机选择指定数量的单词
        const selectedWords = [];
        for (let i = 0; i < this.listenCount; i++) {
          const random = Math.random() * totalWeight;
          const selected = roulette.find(slice => slice.upperBound >= random);
          selectedWords.push(selected);
          roulette = roulette.filter(item => item.english != selected.english)
        }
        return selectedWords;
      },
      startListening() {
        localStorage.removeItem('listening')
        this.isStarted = true;
        this.isFinished = false;
        this.listenRecords = [];
        this.waitingForCorrectAnswer = false;
        this.selectedWords = this.selectWords()
        this.listenToWords();
      },
      listenToWords() {
        this.correctCount = 0;
        this.currentWordIndex = 0;
        this.showCurrentWord();
      },
      showCurrentWord() {
        if (this.currentWordIndex < this.listenCount) {
          this.currentWord = this.selectedWords[this.currentWordIndex];
        }
      },
      checkAnswer() {
        const userAnswer = this.userAnswer.trim().toLowerCase().replace(/[^- a-zA-Z']/g, '').replace('  ', ' ');
        if (userAnswer === '') {
          return
        }
        
        // 如果当前正在等待重新输入正确答案
        if (this.waitingForCorrectAnswer) {
          const correctAnswers = this.currentWord.english.toLowerCase().split('/');
          const isCorrect = correctAnswers.includes(userAnswer);
          if (isCorrect) {
            // 重新输入正确，继续下一题
            this.waitingForCorrectAnswer = false;
            this.userAnswer = '';
            
            // 重新输入正确答案不需要再记录到listenRecords中，因为这道题已经算作错题了
            // 只需要更新当前单词的用户答案
            this.currentWord.userAnswer = userAnswer;
            
            this.showNextWord();
            localStorage.setItem('listening', JSON.stringify({
              'records': this.listenRecords,
              'words': this.selectedWords,
              'current': this.currentWordIndex - 1,
              'correct_count': this.correctCount
            }))
            //判断是否完成当前挑战
            if (this.currentWordIndex >= this.listenCount) {
              //完成挑战，记录挑战时间和结果
              const actualWrongCount = this.listenRecords.filter(record => !record.isCorrect).length;
              const actualCorrectCount = this.listenRecords.filter(record => record.isCorrect).length;
              this.challengeRecords.unshift({
                finish_time: this.formatDate(new Date()),
                words: this.selectedWords,
                records: this.listenRecords, // 保存答题记录
                is_success: actualCorrectCount == this.listenCount,
                wrong_count: actualWrongCount,
                correct_count: actualCorrectCount
              })
              localStorage.setItem('challenge_records', JSON.stringify(this.challengeRecords))
              this.isFinished = true;
              this.isStarted = false;
            }
          } else {
            // 重新输入还是错误，提示用户
            this.showFeedback = true;
            this.feedbackType = 'incorrect';
            this.feedbackMessage = '请重新输入正确答案';
            this.userAnswer = '';
            this.playFeedbackSound(false);
            setTimeout(() => {
              this.hideFeedback();
            }, 1500);
          }
          return;
        }
        
        this.isAnswered = true;
        const correctAnswers = this.currentWord.english.toLowerCase().split('/');
        const isCorrect = correctAnswers.includes(userAnswer);
        this.currentWord.userAnswer = userAnswer;
        this.currentWord.isCorrect = isCorrect;
        this.listenRecords.push({
          word: this.currentWord,
          answer: userAnswer,
          isCorrect: isCorrect
        });

        this.userAnswer = '';
        this.isAnswered = false;
        if (isCorrect) {
          this.correctCount++
        }
        this.saveWordWeight(this.currentWord, isCorrect); //记录单词权重
        
        // 显示答题反馈
        this.showFeedback = true;
        this.feedbackType = isCorrect ? 'correct' : 'incorrect';
        this.feedbackMessage = isCorrect ? '恭喜你，回答正确！' : '很抱歉，回答错误。';
        
        // 播放音效
        this.playFeedbackSound(isCorrect);
        
        if (isCorrect) {
          // 答对了，延迟进入下一题
          setTimeout(() => {
            this.hideFeedback();
            this.showNextWord();
            localStorage.setItem('listening', JSON.stringify({
              'records': this.listenRecords,
              'words': this.selectedWords,
              'current': this.currentWordIndex - 1,
              'correct_count': this.correctCount
            }))
            //判断是否完成当前挑战
            if (this.currentWordIndex >= this.listenCount) {
              //完成挑战，记录挑战时间和结果
              const actualWrongCount = this.listenRecords.filter(record => !record.isCorrect).length;
              const actualCorrectCount = this.listenRecords.filter(record => record.isCorrect).length;
              this.challengeRecords.unshift({
                finish_time: this.formatDate(new Date()),
                words: this.selectedWords,
                records: this.listenRecords, // 保存答题记录
                is_success: actualCorrectCount == this.listenCount,
                wrong_count: actualWrongCount,
                correct_count: actualCorrectCount
              })
              localStorage.setItem('challenge_records', JSON.stringify(this.challengeRecords))
              this.isFinished = true;
              this.isStarted = false;
            }
          }, 1000);
        } else {
          // 答错了，等待用户重新输入正确答案
          this.waitingForCorrectAnswer = true;
          setTimeout(() => {
            this.hideFeedback();
          }, 2000);
        }
      },
      showNextWord() {
        this.currentWordIndex++;
        this.showCurrentWord();
      },
      saveWordWeight(word, isCorrect) {
        let records = this.getWrongWeights()
        let weight = records[word.english] || 0
        if (isCorrect) {
          weight = Math.max(0, weight - 1)
        } else {
          weight += 1
        }
        records[word.english] = weight
        localStorage.setItem('word_weight', JSON.stringify(records))
      },
      getWrongWeights() {
        return JSON.parse(localStorage.getItem('word_weight')) || {};
      },
      showRecordDetail(record) {
        this.selectedRecord = record;
        this.showDetail = true;
      },
      closeDetail() {
        this.showDetail = false;
        this.selectedRecord = null;
      },
      hideFeedback() {
        this.showFeedback = false;
      },
      playFeedbackSound(isCorrect) {
        try {
          const audio = new Audio('key_press_sound.mp3');
          audio.volume = 0.3;
          audio.play();
        } catch (error) {
          console.log('音效播放失败:', error);
        }
      },
      handleKeydown(event) {
        // 移除空格键快速进入下一题的逻辑，避免与自动跳转冲突
      },
      // 格式化日期为指定格式的字符串
      formatDate(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
      }
    }
  });
</script>
<script src="L2DWidget/L2Dwidget.min.js"></script>
<script src="https://gitee.com/layui/layer/blob/master/src/layer.js"></script>
<script>
  const models = [
    'hijiki', //黑猫
    'tororo', //白猫
  ]
  // 生成一个随机索引
  const randomIndex = Math.floor(Math.random() * models.length);
  const model = models[randomIndex]
  L2Dwidget.init({
    "model": {
      jsonPath: "https://unpkg.com/live2d-widget-model-" + model + "@latest/assets/" + model + ".model.json",
      "scale": 1
    },
    "display": {
      "position": "right",
      "width": 150,
      "height": 300,
      "hOffset": 50,
      "vOffset": -20
    },
    "mobile": {
      "show": true,
      "scale": 0.5
    },
    "react": {
      "opacityDefault": 0.7,
      "opacityOnHover": 0.2
    }
  });
</script>
</body>
</html>
